package com.jing.yao.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

public class ExcelUtil {

    private static Sheet initSheet;

    /**
     * 记录日志
     */
    protected static Logger logger = LoggerFactory.getLogger(ExcelUtil.class);

    static {
        initSheet = new Sheet(1, 0);
        initSheet.setSheetName("sheet");
        //设置自适应宽度
        initSheet.setAutoWidth(Boolean.TRUE);
    }

    public static void exportExcel(HttpServletResponse response,
                                   List data, String fileName, Class clazz)
            throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        EasyExcel.write(response.getOutputStream(), clazz).sheet("sheet1").doWrite(data);
    }

    public static <T> ExcelResult<T> importExcel(MultipartFile multipartFile, Integer operationType,
                                                 Class clazz, Validate<T> validate) throws IOException {
        ExcelResult<T> result = new ExcelResult<>();
        EasyExcel.read(multipartFile.getInputStream(), clazz,
                new ReadExcelListener<>(result, validate, operationType))
                .sheet().doRead();
        return result;
    }

    public static void export(List data, String fullFileName, Class clazz) {
        assert fullFileName.endsWith(".xls") : "文件名必须以.xls结尾";
        File file = new File(fullFileName);
        int index = fullFileName.lastIndexOf(File.separator);
        //有的文件路径写死了/,这里做适配
        if (index < 0) {
            index = fullFileName.lastIndexOf("/");
        }
        String fullPath = fullFileName.substring(0, index);
        try {
            new File(fullPath).mkdirs();
            file.createNewFile();
            EasyExcel.write(new FileOutputStream(fullFileName), clazz).sheet("sheet1").doWrite(data);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 生成excle
     *
     * @param filename 绝对路径, 如：/home/chenmingjian/Downloads/aaa.xlsx
     * @param data     数据源
     */
    public static void writeWithTemplate(String filename, Class chazz, List data, HttpServletResponse response) {
        ExcelWriter excelWriter = null;
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(filename, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");

            excelWriter = EasyExcel.write(response.getOutputStream(), chazz).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("sheet1").build();

            excelWriter.write(data, writeSheet);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 千万别忘记finish 会帮忙关闭流
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }


}
